import React, { useState, useEffect, useContext } from "react";
import getConfig from "next/config";
import { Star } from "@styled-icons/boxicons-solid/Star";
import { Star as StarEmpty } from "@styled-icons/boxicons-regular/Star";
import Box from "./Box";
import Text from "./Text";
import Button from "./Button";
import { NotificationContext } from "./Notifications";
import LoadingContext from "../utils/LoadingContext";
import { addMagicPoints } from "./UserMagic";

const Rating = ({ torrentId, userId, token, onRatingComplete }) => {
  const [userRating, setUserRating] = useState(null);
  const [ratingStats, setRatingStats] = useState({
    averageRating: 0,
    ratingCount: 0,
  });
  const [showRatingInput, setShowRatingInput] = useState(false);
  const [score, setScore] = useState(0);

  const { addNotification } = useContext(NotificationContext);
  const { setLoading } = useContext(LoadingContext);

  const {
    publicRuntimeConfig: { SQ_API_URL },
  } = getConfig();

  // 本地存储的评分键
  const localRatingKey = `rating_${userId}_${torrentId}`;
  
  // 从本地存储获取所有评分
  const getLocalRatings = (torrentId) => {
    const localRatings = localStorage.getItem(`ratings_${torrentId}`);
    return localRatings ? JSON.parse(localRatings) : [];
  };
  
  // 保存评分到本地存储
  const saveLocalRating = (userId, torrentId, score) => {
    // 保存用户对此资源的评分
    localStorage.setItem(localRatingKey, JSON.stringify({ score, date: new Date().toISOString() }));
    
    // 更新资源的所有评分
    const allRatings = getLocalRatings(torrentId);
    const existingRatingIndex = allRatings.findIndex(r => r.userId === userId);
    
    if (existingRatingIndex >= 0) {
      allRatings[existingRatingIndex].score = score;
    } else {
      allRatings.push({ userId, score });
    }
    
    localStorage.setItem(`ratings_${torrentId}`, JSON.stringify(allRatings));
    
    // 计算并返回新的统计数据
    return calculateStats(allRatings);
  };
  
  // 计算评分统计
  const calculateStats = (ratings) => {
    if (!ratings || ratings.length === 0) {
      return { averageRating: 0, ratingCount: 0 };
    }
    
    const sum = ratings.reduce((acc, rating) => acc + rating.score, 0);
    return {
      averageRating: sum / ratings.length,
      ratingCount: ratings.length
    };
  };

  useEffect(() => {
    if (userId) {
      // 获取用户对此资源的评分
      const savedRating = localStorage.getItem(localRatingKey);
      if (savedRating) {
        setUserRating(JSON.parse(savedRating));
        setScore(JSON.parse(savedRating).score);
      }
      
      // 获取资源的评分统计
      const allRatings = getLocalRatings(torrentId);
      setRatingStats(calculateStats(allRatings));
    }
  }, [userId, torrentId, localRatingKey]);

  const handleRatingSubmit = async () => {
    setLoading(true);

    try {
      // 检查用户之前是否已经评分过这个种子
      const previousRating = localStorage.getItem(localRatingKey);
      const isNewRating = !previousRating;
      
      // 保存评分到本地存储
      const newStats = saveLocalRating(userId, torrentId, score);
      setRatingStats(newStats);
      setUserRating({ score });
      setShowRatingInput(false);
      
      // 如果是新评分，增加魔力值
      if (isNewRating) {
        const magicPointsEarned = 10;
        addMagicPoints(magicPointsEarned, `评分资源: ${torrentId}`);
        
        // 显示魔力值奖励通知
        addNotification("success", `评分提交成功！获得${magicPointsEarned}点魔力值奖励！`);
      } else {
        addNotification("success", "评分修改成功！");
      }
      
      // 调用父组件传入的完成回调，通知魔力值可能变化
      if (onRatingComplete && isNewRating) {
        onRatingComplete({});
      }
    } catch (e) {
      addNotification("error", `评分提交失败：${e.message}`);
    }

    setLoading(false);
  };

  const renderStars = (value, interactive = false) => {
    return (
      <Box display="flex" alignItems="center">
        {[1, 2, 3, 4, 5].map((star) => (
          <Box
            key={star}
            as={star <= value ? Star : StarEmpty}
            size={24}
            color={star <= value ? "primary" : "grey"}
            style={{ cursor: interactive ? "pointer" : "default" }}
            onClick={() => interactive && setScore(star)}
            mr={1}
          />
        ))}
      </Box>
    );
  };

  return (
    <Box>
      {/* 评分统计 */}
      <Box display="flex" alignItems="center" mb={4}>
        <Box flex="1">
          {renderStars(Math.round(ratingStats.averageRating))}
          <Text mt={2} color="grey">
            {ratingStats.averageRating > 0 ? (
              <>
                {ratingStats.averageRating.toFixed(1)} 满分 5 分 (
                {ratingStats.ratingCount} 个评分)
              </>
            ) : (
              "暂无评分"
            )}
          </Text>
        </Box>
      </Box>

      {/* 用户评分 */}
      {userId && (
        <Box mb={4}>
          {!showRatingInput ? (
            userRating ? (
              <Box display="flex" alignItems="center">
                {renderStars(userRating.score)}
                <Button
                  variant="secondary"
                  size="small"
                  ml={3}
                  onClick={() => setShowRatingInput(true)}
                >
                  修改评分
                </Button>
              </Box>
            ) : (
              <Box display="flex" alignItems="center">
                {renderStars(0)}
                <Button
                  variant="secondary"
                  size="small"
                  ml={3}
                  onClick={() => setShowRatingInput(true)}
                >
                  添加评分
                </Button>
              </Box>
            )
          ) : (
            <Box>
              <Box display="flex" alignItems="center">
                {renderStars(score, true)}
                <Box display="flex" ml={3}>
                  <Button
                    variant="secondary"
                    size="small"
                    mr={2}
                    onClick={() => setShowRatingInput(false)}
                  >
                    取消
                  </Button>
                  <Button
                    type="button"
                    size="small"
                    onClick={handleRatingSubmit}
                  >
                    提交
                  </Button>
                </Box>
              </Box>
            </Box>
          )}
        </Box>
      )}
    </Box>
  );
};

export default Rating;
